package com.wantup.miaosha.service.impl;

import com.wantup.miaosha.entity.TblUser;
import com.wantup.miaosha.entity.TblUser2;
import com.wantup.miaosha.mapper.TblUserMapper;
import com.wantup.miaosha.pojo.UserPojo;
import com.wantup.miaosha.service.UserService;
import com.wantup.miaosha.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private TblUserMapper tblUserMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public TblUser getUserInofByIdService(Integer id) throws Exception {
        return this.tblUserMapper.getUserInfoById(id);
    }

    /**
     * 用户插入
     *
     * @param tblUser
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public int userRegisterService(TblUser2 tblUser) throws Exception {
        //int i = 1/0;
        UserPojo userPojo = new UserPojo();
        userPojo.setName(tblUser.getName()).setPassword(tblUser.getPassword());
        Integer integer = this.tblUserMapper.userExistMapper(userPojo);
        log.info("是否存在 --> " + integer);
        if (integer == 1) {
            return 0;
        }
        return this.tblUserMapper.userRegisterMapper(tblUser);
    }


    @Override
    public TblUser userLoginService(UserPojo userPojo) throws Exception {
        if (userPojo.getPassword() == null || StringUtils.isEmpty(userPojo.getPassword())) {
            return this.tblUserMapper.userLoginMapper2(userPojo.getName());
        }
        return this.tblUserMapper.userLoginMapper(userPojo);
    }


    @Override
    public TblUser getByUserId(String name) {
        return this.tblUserMapper.getUserById(name);
    }

    /**
     * @param token
     * @return
     * @throws Exception
     */
    @Override
    public TblUser getUserByTokenService(String token) throws Exception {
        TblUser tblUser = redisUtils.get(token, TblUser.class);
        log.info("获取redis中的 TblUser --> " + tblUser);

        return tblUser;
    }
}
